package com.example.mobilesafe.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import com.example.mobilesafe.db.AppLockOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class AppLockDao {

    // 0.声明SQLite工具类
    private final AppLockOpenHelper mApplockOpenHelper;

    private Context context;

    /**
     * 让AppLockDao实现单例模式（懒汉）
     * 1.私有化构造方法
     * 2.声明一个当前类的对象
     * 3.提供获取单例方法，如果当前类的对象为空，创建一个新的
      */

    /**
     * 1.私有化构造方法
     * @param context 上下文环境
     */
    private AppLockDao(Context context) {
        this.context = context;
        // 创建数据库及其表结构
        mApplockOpenHelper = new AppLockOpenHelper(context, "applock.db", null, 1);
    }

    // 2.声明一个当前类对象
    private static AppLockDao applockDao;

    /**
     * 3.提供获取单例方法
     * @param context 上下文环境
     * @return
     */
    public static AppLockDao getInstance(Context context){
        if (applockDao == null){
            applockDao = new AppLockDao(context);
        }
        return applockDao;
    }

    /**
     * 4.插入数据
     * @param packagename 待插入的应用包名
     */
    public void insert(String packagename){
        SQLiteDatabase db = mApplockOpenHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("packagename",packagename);
        db.insert("applock",null,values);
        db.close();
        context.getContentResolver().notifyChange(Uri.parse("content://applock/change"),null);
    }

    /**
     * 5.删除数据
     * @param packagename 待插入的应用包名
     */
    public void delete(String packagename){
        SQLiteDatabase db = mApplockOpenHelper.getWritableDatabase();
        db.delete("applock","packagename = ?",new String[]{packagename});
        db.close();
        context.getContentResolver().notifyChange(Uri.parse("content://applock/change"),null);
    }

    /**
     * 6.查询所有数据
     */
    public List<String> queryAll(){
        SQLiteDatabase db = mApplockOpenHelper.getWritableDatabase();
        Cursor cursor = db.query("applock", new String[]{"packagename"}, null, null, null, null, null);
        List<String> lockPackageList = new ArrayList<>();
        while (cursor.moveToNext()){
            lockPackageList.add(cursor.getString(0));
        }
        cursor.close();
        db.close();
        return lockPackageList;
    }
}